package a66weding.com.jiehuntong.fragment;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import com.google.gson.Gson;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import a66weding.com.jiehuntong.R;
import a66weding.com.jiehuntong.activity.ElectronicInvitationActivity;
import a66weding.com.jiehuntong.activity.WriteStoryActivity;
import a66weding.com.jiehuntong.activity.imageupload.activity.AlbumActivity;
import a66weding.com.jiehuntong.activity.imageupload.activity.util.Bimp;
import a66weding.com.jiehuntong.activity.imageupload.activity.util.ImageItem;
import a66weding.com.jiehuntong.adapter.AMDragRateAdapter;
import a66weding.com.jiehuntong.application.DataWareHourse;
import a66weding.com.jiehuntong.beans.ErrorBean;
import a66weding.com.jiehuntong.beans.HttpRequestBean;
import a66weding.com.jiehuntong.beans.ImageStoryBean;
import a66weding.com.jiehuntong.beans.SimpleBean;
import a66weding.com.jiehuntong.beans.SuccessBean;
import a66weding.com.jiehuntong.common.MessageEvent;
import a66weding.com.jiehuntong.common.utils.CUtils;
import a66weding.com.jiehuntong.common.utils.FileUtil;
import a66weding.com.jiehuntong.common.utils.LogUtil;
import a66weding.com.jiehuntong.common.utils.Tools;
import a66weding.com.jiehuntong.common.utils.Utils;
import a66weding.com.jiehuntong.http.HttpHandleUtil;
import a66weding.com.jiehuntong.http.OnNetResultListener;
import a66weding.com.jiehuntong.http.RequestCode;
import a66weding.com.jiehuntong.view.ResizeLayout;
import a66weding.com.jiehuntong.view.dragsortlistview.DragSortListView;
public class ImageStoryFragment extends Fragment implements View.OnClickListener, OnNetResultListener, AMDragRateAdapter.deleteCallback {
    private Button btn_add_img;
    private static final int PERMISSION_SDCARD = 4;
    private static final int PERMISSION_CAMERA = 5;
    ArrayList<File> zoomFiles = new ArrayList<>();
    private static final int TAKE_PICTURE = 0, CROPIMAGE = 2;
    private Dialog dialog;
    private DragSortListView dslvList;
    private AMDragRateAdapter amDragRateAdapter;
    private WriteStoryActivity mWriteStoryActivity;
    private List<ImageStoryBean.DataBean> imageStoryList;
    public static String HEAD_PHOTO_NAME = "crop_story_image.jpg";//裁剪后图片名称
    public static final String TAKE_PHOTO_FILE_NAME = "story.jpg";//拍照后图片名称
    private static final String TAG = "777";
    private static final int BIGGER = 1;
    private static final int SMALLER = 2;
    private static final int MSG_RESIZE = 1;
    private View view;
    private int uId;
    private List<String> tempList = new ArrayList<String>();
    private boolean isUpLoadFinish = false;//标记当前是否是上传完成照片，如果是上传完照片，直接跳转到listview最下位置

    class InputHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_RESIZE: {
                    if (msg.arg1 == BIGGER) {
                    /*   以前按照键盘收缩方式，暂时不用了 for (int i = 0; i < tempList.size(); i++) {//遍历整个暂存区域的数据
                            String oldValues = (String) tempList.get(i);//获得暂存区域的旧数据
                            ImageStoryBean.DataBean item = (ImageStoryBean.DataBean) dslvList.getAdapter().getItem(i);//获得当前listview的item数据
                            String newValues = item.getNvc_PicStory();//获得数据内容
                            if (oldValues == null) {//当上次数据为空,直接提交本次不再做比对防止崩溃
                                upDataContent(item.getI_Id(), newValues);
                                continue;
                            }
                            if (!oldValues.equals(newValues)) {//不一致则请求联网更新
                                upDataContent(item.getI_Id(), newValues);
                            }
                        }*/
                    } else {
               /*     以前按照键盘收缩方式，暂时不用了     int count = dslvList.getAdapter().getCount();//获得当前listview的适配器总条数
                        tempList.clear();//清空暂存集合
                        for (int i = 0; i < count; i++) {//遍历每条item数据并暂存到暂存区域
                            ImageStoryBean.DataBean item = (ImageStoryBean.DataBean) dslvList.getAdapter().getItem(i);
                            tempList.add(item.getNvc_PicStory());
                        }
                    }*/
                    }
                }
                break;
            }
        }
    }

    private InputHandler mHandler = new InputHandler();

    //获得祝福语暂存
    public void cacheBlessingText() {
        if (dslvList.getAdapter() != null) {
            int count = dslvList.getAdapter().getCount();//获得当前listview的适配器总条数
            tempList.clear();//清空暂存集合
            for (int i = 0; i < count; i++) {//遍历每条item数据并暂存到暂存区域
                ImageStoryBean.DataBean item = (ImageStoryBean.DataBean) dslvList.getAdapter().getItem(i);
                tempList.add(item.getNvc_PicStory());
            }
        }
    }

    private int textChangeCount;//统计改变了多少文本
    private boolean textIsChanged = false;//文本是否变过

    //对比祝福语
    public void equalsBlessingText() {
        textChangeCount = 0;
        //统计改变了多少条数据
        for (int i = 0; i < tempList.size(); i++) {//遍历整个暂存区域的数据
            String oldValues = (String) tempList.get(i);//获得暂存区域的旧数据
            ImageStoryBean.DataBean item = (ImageStoryBean.DataBean) dslvList.getAdapter().getItem(i);//获得当前listview的item数据
            String newValues = item.getNvc_PicStory();//获得数据内容
            if (oldValues == null) {//当上次数据为空,直接提交本次不再做比对防止崩溃
                textChangeCount++;
                continue;
            }
            if (!oldValues.equals(newValues)) {//不一致则请求联网更新
                textChangeCount++;
            }
        }
        Log.i(TAG, "equalsBlessingText: 一共改变了" + textChangeCount + "条");
        //开始网络请示设置当前文本
        for (int i = 0; i < tempList.size(); i++) {//遍历整个暂存区域的数据
            String oldValues = (String) tempList.get(i);//获得暂存区域的旧数据
            ImageStoryBean.DataBean item = (ImageStoryBean.DataBean) dslvList.getAdapter().getItem(i);//获得当前listview的item数据
            String newValues = item.getNvc_PicStory();//获得数据内容
            if (oldValues == null) {//当上次数据为空,直接提交本次不再做比对防止崩溃
                upDataContent(item.getI_Id(), newValues);
                continue;
            }
            if (!oldValues.equals(newValues)) {//不一致则请求联网更新
                upDataContent(item.getI_Id(), newValues);
            }
        }
    }

    @Override
    public void onResume() {
        isUpLoadFinish = false;
        cacheBlessingText();
        super.onResume();
    }

    @Subscribe
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        isUpLoadFinish = false;
        view = inflater.inflate(R.layout.fragment_image_story, container, false);
        mWriteStoryActivity = (WriteStoryActivity) getActivity();
        //计算键盘是否弹出
        ResizeLayout layout = (ResizeLayout) view.findViewById(R.id.root_layout);
        layout.setOnResizeListener(new ResizeLayout.OnResizeListener() {
            public void OnResize(int w, int h, int oldw, int oldh) {
                int change = BIGGER;
                if (h < oldh) {
                    change = SMALLER;
                }
                Message msg = new Message();
                msg.what = 1;
                msg.arg1 = change;
                mHandler.sendMessage(msg);
            }
        });
        uId = DataWareHourse.getInstance().getmUser().getData().get(0).getI_Id();
        //请求网络图片故事列表
        getImageList();
        initView(view);
        Bimp.getTempSelectBitmap().clear();//清除之前选择的图片选项
        EventBus.getDefault().register(this);
        return view;
    }

    ArrayList<ImageItem> tempSelectBitmapList;//这个是选择图片后存放图片的集合

    @Subscribe
    public void onEventMsg(MessageEvent msg) {
        tempSelectBitmapList = Bimp.getInstance().getTempSelectBitmap();//获得已经选择的存放在了这里
        if (tempSelectBitmapList != null && tempSelectBitmapList.size() > 0) {
            Tools.showSimpleDialog(mWriteStoryActivity, "已选" + tempSelectBitmapList.size() + "张图片,是否上传?", "取消", "确定", new Tools.ClickListenerInterface() {
                @Override
                public void doConfirm() {
                    hd.sendEmptyMessage(1);
//                    btn_add_img.setEnabled(false);
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            for (ImageItem ii : tempSelectBitmapList) {
                                //  uploadfile(new File(ii.getImagePath()));
                                zoomBitmap(new File(ii.getImagePath()));
                            }
                            hd.sendEmptyMessage(2);
                        }
                    }).start();

                }

                @Override
                public void doCancel() {
                }
            });
        }
    }

    //请求网络图片故事列表
    private void getImageList() {
        String url = RequestCode.SURL + RequestCode.IMAGESTORY + uId;
        HttpRequestBean httpRequestBean = new HttpRequestBean(RequestCode.GETREQUEST, url, this, ImageStoryBean.class, RequestCode.IMAGESTORY);
        HttpHandleUtil.executeCommonGet(mWriteStoryActivity, httpRequestBean);
    }

    private void initView(View view) {
        btn_add_img = (Button) view.findViewById(R.id.btn_add_img);
        btn_add_img.setOnClickListener(this);
        dslvList = (DragSortListView) view.findViewById(R.id.dslvList);
        dslvList.setAlpha(1);
        dslvList.setDragEnabled(false);//设置不可拖动
        //拖动或者删除更是数据
        dslvList.setDropListener(new DragSortListView.DragSortListener() {
            @Override
            public void drag(int from, int to) {
            }

            @Override
            public void drop(int from, int to) {
                if (from != to) {
                    ImageStoryBean.DataBean fromItem = (ImageStoryBean.DataBean) amDragRateAdapter.getItem(from);//得到listview的适配器
                    ImageStoryBean.DataBean toItem = (ImageStoryBean.DataBean) amDragRateAdapter.getItem(to);//得到listview的适配器
                    amDragRateAdapter.remove(from);//在适配器中”原位置“的数据。
                    amDragRateAdapter.insert(fromItem, to);//在目标位置中插入被拖动的控件。
                    HttpRequestBean httpRequestBean = new HttpRequestBean();
                    int count = dslvList.getAdapter().getCount();
                    StringBuffer sb = new StringBuffer();
                    for (int i = 0; i < count; i++) {
                        ImageStoryBean.DataBean item = (ImageStoryBean.DataBean) dslvList.getAdapter().getItem(i);
                        int i_id = item.getI_Id();
                        sb.append(i_id + ",");
                        if (i == count - 1) {
                            sb.append(i_id);
                        }
                    }
                    httpRequestBean.setUrl(RequestCode.SURL + RequestCode.IMAGESTORYORDER + uId + "&ids=" + sb.toString());
                    httpRequestBean.setClazz(SimpleBean.class);
                    httpRequestBean.setRequestMethod(RequestCode.POSTEQUEST);
                    httpRequestBean.setListener(ImageStoryFragment.this);
                    httpRequestBean.setRequestCode(RequestCode.IMAGESTORYORDER);
                    HttpHandleUtil.executeCommonGet(getActivity(), httpRequestBean);
                }
            }

            @Override
            public void remove(int which) {
            }
        });
    }

    public void upLoadImgCheck() {
        View view = getActivity().getLayoutInflater().inflate(R.layout.activity_tools_dialog_photo, null);
        Button photoBtn = (Button) view.findViewById(R.id.dialog_photo_button);
        Button cameraBtn = (Button) view.findViewById(R.id.dialog_camera_button);
        Button quxiaoBtn = (Button) view.findViewById(R.id.dialog_quxiao_button);
        if (dialog == null) {
            dialog = new Dialog(getActivity(), R.style.transparentFrameWindowStyle);
        }
        photoBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (dialog != null && dialog.isShowing()) {
                    dialog.dismiss();
                }
                //进入相册浏览界面;
                Bimp.getTempSelectBitmap().clear();//清除之前选择的图片选项
                Intent intent = new Intent(getActivity(), AlbumActivity.class);
                startActivity(intent);
                mWriteStoryActivity.overridePendingTransition(R.anim.activity_translate_in, R.anim.activity_translate_out);

            }
        });
        cameraBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (dialog != null && dialog.isShowing()) {
                    dialog.dismiss();
                }
                showCamera();
            }
        });
        quxiaoBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (dialog != null && dialog.isShowing()) {
                    dialog.dismiss();
                }
            }
        });
        dialog.setContentView(view, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT));
        Window window = dialog.getWindow();
        // 设置显示动画
        window.setWindowAnimations(R.style.main_menu_animstyle);
        WindowManager.LayoutParams wl = window.getAttributes();
        wl.x = 0;
        wl.y = getActivity().getWindowManager().getDefaultDisplay().getHeight();
        // 以下这两句是为了保证按钮可以水平满屏
        wl.width = ViewGroup.LayoutParams.MATCH_PARENT;
        wl.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        // 设置显示位置
        dialog.onWindowAttributesChanged(wl);
        // 设置点击外围解散
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_add_img:
                upLoadImgCheck();
                break;
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        doNext(requestCode, grantResults);
    }

    private void doNext(int requestCode, int[] grantResults) {
        if (requestCode == PERMISSION_CAMERA) {
            if (grantResults.length > 0 && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
                Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                //下面这句指定调用相机拍照后的照片存储的路径
                File imgFile = new File(FileUtil.getImgFile(getActivity()), TAKE_PHOTO_FILE_NAME);
                openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(imgFile));
                startActivityForResult(openCameraIntent, TAKE_PICTURE);
            } else {
                CUtils.showToast("请打开手机拍照权限后在操作");
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case TAKE_PICTURE://照相
                final File temp = new File(FileUtil.getImgFile(getActivity()), TAKE_PHOTO_FILE_NAME);
                if (temp != null && temp.exists()) {
                    Tools.showSimpleDialog(getActivity(), "是否上传拍摄的图片", "取消", "确定", new Tools.ClickListenerInterface() {
                        @Override
                        public void doConfirm() {
                            hd.sendEmptyMessage(1);
//                            btn_add_img.setEnabled(false);
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    zoomBitmap(temp);
                                    hd.sendEmptyMessage(2);
                                }
                            }).start();
                        }

                        @Override
                        public void doCancel() {

                        }
                    });

                }

                //  startPhotoZoom(Uri.fromFile(temp));
                break;

        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        Bimp.getTempSelectBitmap().clear();//清除之前选择的图片选项
    }

    /*
     * 压缩图片文件大小
     */
    public void zoomBitmap(File file) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        options.inPreferredConfig = Bitmap.Config.RGB_565;
        BitmapFactory.decodeFile(file.getPath(), options);
        //如果当前图片大于系统可用内存,压缩图片大小
        options.inSampleSize = calculateInSampleSize(options);
        //图片大于1.5M压缩
        if (file.length() / 1024.0 / 1024 > 1.5) {
            options.inJustDecodeBounds = false;
            String s = file.getName().substring(0, file.getName().lastIndexOf(".")) + "copy" + file.getName().substring(file.getName().lastIndexOf("."), file.getName().length());
            Bitmap bitmap = BitmapFactory.decodeFile(file.getPath(), options);
            //文件输出路径
            File defaultFile = FileUtil.getDefaultFile(s);
            FileOutputStream out = null;
            try {
                //文件输出流
                out = new FileOutputStream(defaultFile);
                //压缩,格式百分比,如果是100则不压缩,输出文件路径
                bitmap.compress(Bitmap.CompressFormat.JPEG, 60, out);
                out.flush();
                out.close();
                bitmap.recycle();  //回收图片所占的内存
                zoomFiles.add(defaultFile);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (bitmap != null && !bitmap.isRecycled()) {
                    bitmap.recycle();  //回收图片所占的内存
                    System.gc();//提醒系统及时回收
                }
            }
        } else {
            zoomFiles.add(file);
        }
    }

    //计算大小
    private int calculateInSampleSize(BitmapFactory.Options options) {
        // Raw height and width of image
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;
        if (height / 1000.0 > 3 || width / 1000.0 > 3) {
            inSampleSize = 3;
        } else if (height / 1000.0 > 2 || width / 1000.0 > 2) {
            inSampleSize = 2;
        }
        return inSampleSize;
    }

    /**
     * 图片排序
     */
    public void order() {
        if (amDragRateAdapter != null && amDragRateAdapter.getCount() > 1) {
            equalsBlessingText();
            amDragRateAdapter.notifyDataSetChanged();
            if (mWriteStoryActivity.isEdit) {
                dslvList.setDragEnabled(true);
            } else {
                dslvList.setDragEnabled(false);
            }
        } else {
            mWriteStoryActivity.order.setText("排序");
            CUtils.showToast("当前数据过少不可排序");
        }
    }

    boolean removeFlag = false;//判断是否是移除
    int removeIndex = -1;//移除的下标如果是-1则不移除

    @Override
    public void onSucess(SuccessBean sucessbean) {
        Object data = sucessbean.getData();
        if (data instanceof ImageStoryBean) {
            ImageStoryBean imageStoryBean = (ImageStoryBean) data;
            if (imageStoryBean != null && imageStoryBean.getResCode() != null) {
                if (imageStoryBean.getResCode().equals("0000")) {
                    //设置数据到list
                    imageStoryList = imageStoryBean.getData();
                    amDragRateAdapter = null;
                    amDragRateAdapter = new AMDragRateAdapter(mWriteStoryActivity, imageStoryList, this, this);
                    dslvList.setAdapter(amDragRateAdapter);
                    if (isUpLoadFinish) {
                        dslvList.setSelection(amDragRateAdapter.getCount());
                    }
                    cacheBlessingText();
                } else {
                    CUtils.showToast(imageStoryBean.getMsg());
                }
            }
        } else if (data instanceof SimpleBean) {
            String inf = sucessbean.getInf();
            SimpleBean simpleBean = (SimpleBean) data;
            //RequestCode.CHANGEIMAGETEXT
            if (simpleBean != null && simpleBean.getResCode() != null) {
                if (simpleBean.getResCode().equals("0000")) {
                    //删除一个图片故事
                    if (removeFlag) {
                        CUtils.showToast("删除" + simpleBean.getMsg());
                        if (removeIndex > -1) {
                            amDragRateAdapter.remove(removeIndex);
                            removeFlag = false;
                            cacheBlessingText();
                            //通知我的电子请柬更新界面
                            mWriteStoryActivity.sendBroadcast(new Intent(ElectronicInvitationActivity.ACTION_REFRESH_INVITATION));
                        }
                    }
                    //修改图片故事
                    if (inf.equals(RequestCode.CHANGEIMAGETEXT)) {
                        textChangeCount--;
                        if (textChangeCount == 0 && textIsChanged) {
                            Log.i(TAG, "onSucess: 全部更改文本完成发送广播刷新页面");
                            //通知我的电子请柬更新界面
                            mWriteStoryActivity.sendBroadcast(new Intent(ElectronicInvitationActivity.ACTION_REFRESH_INVITATION));
                        }
                    }
                } else {
                    CUtils.showToast(simpleBean.getMsg());
                }
            }
        }
    }

    @Override
    public void onError(ErrorBean errorBean) {
        CUtils.showToast("数据请求失败");
    }

    /**
     * 根据下标获取条目删除图片故事
     */
    @Override
    public void deleteItem(int position) {
        equalsBlessingText();//删除前提交一次修改内容
        removeFlag = true;
        removeIndex = position;
        HttpRequestBean httpRequestBean = new HttpRequestBean();
        ImageStoryBean.DataBean item = (ImageStoryBean.DataBean) dslvList.getAdapter().getItem(position);
        httpRequestBean.setUrl(RequestCode.SURL + RequestCode.IMAGESTORYDELDTE + item.getI_Id());
        httpRequestBean.setClazz(SimpleBean.class);
        httpRequestBean.setRequestMethod(RequestCode.POSTEQUEST);
        httpRequestBean.setListener(this);
        httpRequestBean.setRequestCode(RequestCode.IMAGESTORYORDER);
        HttpHandleUtil.executeCommonGet(mWriteStoryActivity, httpRequestBean);
    }

    /**
     * 根据图片id修改内容
     */
    public void upDataContent(int i_id, String changeContent) {
        textIsChanged = true;
        if (changeContent == null) {
            changeContent = "";
        }
        String url = RequestCode.SURL + RequestCode.CHANGEIMAGETEXT + i_id + "&content=" + Utils.URLEncode(changeContent);
        HttpRequestBean httpRequestBean = new HttpRequestBean(RequestCode.POSTEQUEST, url, this, SimpleBean.class, RequestCode.CHANGEIMAGETEXT);
        LogUtil.d(TAG, "修改图片故事" + httpRequestBean.getUrl());
        HttpHandleUtil.executeCommonGet(mWriteStoryActivity, httpRequestBean);
    }

    //拍照
    public void showCamera() {
        if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(getActivity(), new String[]
                    {Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_SDCARD);
        } else {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            //下面这句指定调用相机拍照后的照片存储的路径
            File imgFile = new File(FileUtil.getImgFile(getActivity()), TAKE_PHOTO_FILE_NAME);
            if (imgFile.exists())
                imgFile.delete();//如果图片存在删除,防止上次的照片照完后,本次不拍照依然能裁剪
            //下面这句指定调用相机拍照后的照片存储的路径
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(imgFile));
            this.startActivityForResult(intent, TAKE_PICTURE);
        }
    }

    /**
     * 控制表单格式一次上传一个
     * WeddingMobileApi/UpStoryPicUid?Token={Token}&uid={uid}
     */
    ArrayList<File> failsFile = new ArrayList<>();

    private void uploadfile(final File saveFile) {
        LogUtil.i(TAG, "上传图片位置: " + saveFile.getPath() + "大小:" + saveFile.length());
        LogUtil.i(TAG, "一次上传一个表单文件控制中 ");
        // 弹框
        if (countUploading > 1) {
            Tools.showWaitDialog(getActivity(), "上传中...(" + (countUploading - zoomFiles.size() + 1) + "/" + countUploading + ")", false);
        } else {
            Tools.showWaitDialog(getActivity(), "上传中...", false);
        }
        //图片上传地址
        final String url = RequestCode.SURL + RequestCode.UPLOADIMAGESTORY + uId;
        new Thread() {
            @Override
            public void run() {
                String result = uploadFile(saveFile, url);
                LogUtil.i(TAG, "上传图片回馈结果: " + result);
                if (!TextUtils.isEmpty(result)) {
                    Gson gson = new Gson();
                    SimpleBean simpleBean = gson.fromJson(result, SimpleBean.class);
                    if (!simpleBean.getResCode().equals("0000")) {
                        File file = zoomFiles.get(0);
                        failsFile.add(file);
                    } else {
                        //通知我的电子请柬更新界面
                        mWriteStoryActivity.sendBroadcast(new Intent(ElectronicInvitationActivity.ACTION_REFRESH_INVITATION));
                        hd.sendEmptyMessage(0);
                    }

                }

            }
        }.start();
    }

    @Override
    public void onPause() {
        equalsBlessingText();
        Tools.dismissWaitDialog();
        super.onPause();
    }

    private int countUploading;// 上传图片张数

    Handler hd = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    isUpLoadFinish = true;
                    if (zoomFiles != null && zoomFiles.size() > 0) {
                        zoomFiles.remove(0);
                        LogUtil.i(TAG, "移除,剩余" + zoomFiles.size());
                        if (zoomFiles.size() > 0) {
                            LogUtil.i(TAG, "继续");
                            uploadfile(zoomFiles.get(0));
                        }
                    }
                    if (zoomFiles.size() == 0) {
                        // 取消弹框
                        Tools.dismissWaitDialog();

//                        btn_add_img.setEnabled(true);
                        mWriteStoryActivity.sendBroadcast(new Intent(ElectronicInvitationActivity.ACTION_REFRESH_INVITATION)); //请柬内容有修改后调用该行代码
                        //请柬内容有修改后调用该行代码
                        mWriteStoryActivity.sendBroadcast(new Intent(ElectronicInvitationActivity.ACTION_REFRESH_INVITATION));
                        if (failsFile.size() > 0) {
                            Tools.showSimpleDialog(getActivity(), failsFile.size() + "张图片上传失败", "取消", "重试", new Tools.ClickListenerInterface() {
                                @Override
                                public void doConfirm() {
                                    for (File f : failsFile) {
                                        zoomFiles.add(f);
                                    }
                                    failsFile.clear();
                                    countUploading = zoomFiles.size();
                                    uploadfile(zoomFiles.get(0));
                                }

                                @Override
                                public void doCancel() {
                                    failsFile.clear();
                                }
                            });
                        }
                        //刷新界面
                        getImageList();
                    }
                    break;
                case 1:
                    Tools.showWaitDialog(getActivity(), "获取图片...", true);
                    break;
                case 2:
                    //upLoads();//多文件一次请求上传提交
                    countUploading = zoomFiles.size();
                    uploadfile(zoomFiles.get(0));
                    if (tempSelectBitmapList != null) {
                        tempSelectBitmapList.clear();//清空
                    }
                    break;
                default:
                    break;
            }
        }
    };

    /**
     * 表单格式一次上传一个
     */
    public String uploadFile(File file, String RequestURL) {
        LogUtil.i(TAG, "表单上传文件一个");
        String result = "";
        String BOUNDARY = UUID.randomUUID().toString();
        //边界标识 随机生成
        String PREFIX = "--", LINE_END = "\r\n";
        String CONTENT_TYPE = "multipart/form-data"; //内容类型
        try {
            URL url = new URL(RequestURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(10 * 100000);
            conn.setConnectTimeout(10 * 100000);
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST"); //请求方式
            conn.setRequestProperty("Charset", "utf-8");
            //设置编码
            conn.setRequestProperty("connection", "keep-alive");
            conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);
            if (file != null) {
                /**  当文件不为空，把文件包装并且上传 */
                OutputStream outputSteam = conn.getOutputStream();
                DataOutputStream dos = new DataOutputStream(outputSteam);
                StringBuffer sb = new StringBuffer();
                sb.append(PREFIX);
                sb.append(BOUNDARY);
                sb.append(LINE_END);
                sb.append("Content-Disposition: form-data; name=\"img\"; filename=\"" + file.getName() + "\"" + LINE_END);
                sb.append("Content-Type: application/octet-stream; charset=utf-8" + LINE_END);
                sb.append(LINE_END);
                dos.write(sb.toString().getBytes());
                InputStream is = new FileInputStream(file);
                byte[] bytes = new byte[1024];
                int len = 0;
                while ((len = is.read(bytes)) != -1) {
                    dos.write(bytes, 0, len);
                }
                is.close();
                dos.write(LINE_END.getBytes());
                byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes();
                dos.write(end_data);
                dos.flush();
                /**
                 * 获取响应码 200=成功
                 * 当响应成功，获取响应的流
                 */
                int res = conn.getResponseCode();
                LogUtil.d("6969", "响应吗" + res);
                if (res == 200) {
                    // 读取返回数据
                    StringBuffer strBuf = new StringBuffer();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                    String line = null;
                    while ((line = reader.readLine()) != null) {
                        strBuf.append(line).append("\n");
                    }
                    result = strBuf.toString();
                    reader.close();

                    return result;
                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
/*    *//**
     * 多文件一次接口上传
     *//*
    private void uploadMultiFiles() {
        final String url = RequestCode.SURL + RequestCode.UPLOADIMAGESTORY + uId;
        // 弹框
        Tools.showWaitDialog(getActivity(), "上传中...", false);
        HttpManager xhttp = x.http();
        RequestParams requestParams = new RequestParams(url);
        if (zoomFiles != null && zoomFiles.size() > 0) {
            for (File f : zoomFiles) {
                Log.i(TAG, "添加上传文件: " + f.getName());
                requestParams.addBodyParameter("img", f);
            }
            //zoomFiles.clear();
            xhttp.post(requestParams, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    Tools.dismissWaitDialog();
                    //刷新界面
                    getImageList();
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    Tools.dismissWaitDialog();
                    LogUtil.i("httpUtils", "postError:" + ex.toString());
                    CUtils.showToast("上传失败 ");
                }

                @Override
                public void onCancelled(CancelledException cex) {
                    CUtils.showToast("取消 ");
                }

                @Override
                public void onFinished() {

                }
            });
        }
    }*/
/**
 * 表单格式多文件上传
 *//*

    public String uploadMultiFiles(String RequestURL) {
        Log.i(TAG, "多文件一次上传中");
        String result = "";
        String BOUNDARY = UUID.randomUUID().toString();
        //边界标识 随机生成
        String PREFIX = "--", LINE_END = "\r\n";
        String CONTENT_TYPE = "multipart/form-data"; //内容类型
        try {
            URL url = new URL(RequestURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(60 * 100000);
            conn.setConnectTimeout(60 * 100000);
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST"); //请求方式
            conn.setRequestProperty("Charset", "utf-8");
            //设置编码
            conn.setRequestProperty("connection", "keep-alive");
            conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);
            /*/
/**  当文件不为空，把文件包装并且上传 *//*
*/
/*
            OutputStream outputSteam = conn.getOutputStream();
            DataOutputStream dos = new DataOutputStream(outputSteam);
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < zoomFiles.size(); i++) {
                File file = zoomFiles.get(i);
               // 1
                sb.append(PREFIX);
                sb.append(BOUNDARY);
                sb.append(LINE_END);
                //2
                sb.append("Content-Disposition: form-data; name=\"img\"; filename=\"" + file.getName() + "\"" + LINE_END);
                sb.append("Content-Type: application/octet-stream; charset=utf-8" + LINE_END);
               // 3
                sb.append(LINE_END);
                dos.write(sb.toString().getBytes());
               // 4
                InputStream isPic = new FileInputStream(file);
                byte[] bytes = new byte[1024];
                int len = -1;
                long count = 0;

                while ((len = isPic.read(bytes)) != -1) {
                    dos.write(bytes, 0, len);
                }
                dos.writeBytes(LINE_END);
                isPic.close();
                InputStream is = new FileInputStream(file);
            }
            zoomFiles.clear();
            dos.write(LINE_END.getBytes());
            byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes();
            dos.write(end_data);
            dos.flush();
            /*/
/*获取响应码 200=成功 当响应成功，获取响应的流
            int res = conn.getResponseCode();
            if (res == 200) {
                // 读取返回数据
                StringBuffer strBuf = new StringBuffer();
                BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                String line = null;
                while ((line = reader.readLine()) != null) {
                    strBuf.append(line).append("\n");
                }
                result = strBuf.toString();
                reader.close();
                return result;
            }
            dos.close();


        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

   */
/* public  void upLoads(){
        Log.i(TAG, " 表单格式多文件一次上传");
        // 弹框
        Tools.showWaitDialog(getActivity(), "上传中...", false);
        //图片上传地址
        final String url = RequestCode.SURL + RequestCode.UPLOADIMAGESTORY + uId;
        new Thread() {
            @Override
            public void run() {
                String result = uploadMultiFiles(url);
                Log.i(TAG, "上传图片回馈结果: 表单格式多文件一次接口写入 " + result);
                if (!TextUtils.isEmpty(result)) {
                    // 取消弹框
                    Tools.dismissWaitDialog();
                    //请柬内容有修改后调用该行代码
                    mWriteStoryActivity.sendBroadcast(new Intent(ElectronicInvitationActivity.ACTION_REFRESH_INVITATION));
                    //刷新界面
                    getImageList();
                }
            }
        }.start();
    }*//**/

}
